﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq.SqlClient;
using S9Engine;


public partial class Advertise : Parser
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            Session["CurrentPage"] = "Advertise.aspx";
            
            if (!CheckLogin()) Response.Redirect("login.aspx");

            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);

            string type = Request["type"] ?? "default";

            _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Meta);

            switch (type)
            {
                case "default":
                    {
                        LoadFile("advertise.html", false);
                        LoadAdvertises();
                        break;
                    }
                case "add":
                    {
                        LoadFile("advertise_add.html", false);
                        LoadAdvertiseByID(null);
                        break;
                    }
                case "edit":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("advertise.aspx");
                        }
                        else
                        {
                            LoadFile("advertise_add.html", false);
                            LoadAdvertiseByID(long.Parse(Request["id"]));
                        }
                        break;
                    }
                case "delete":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("advertise.aspx");
                        }
                        else
                        {
                            DeleteAdvertiseByID(long.Parse(Request["id"]));
                        }
                        break;
                    }
                default: goto case "default";
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadAdvertises()
    {
        try
        {
            List<Advertises> advertises = _DR.Advertises.Where(a => a.LanguageCode.Equals(_currentLanguage)).OrderByDescending(a => a.ID).ToList();

            string search = Request["search"] ?? string.Empty;

            if (!string.IsNullOrEmpty(search))
            {
                advertises = advertises.Where(a => a.Name.ToLower().Contains(search) || a.Description.ToLower().Contains(search) || a.Content.ToLower().Contains(search)).ToList();
                _parser.Assign("searchValue", search);
            }

            double totalRecord = advertises.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);

            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("advertiseID", advertises[i].ID.ToString());
                    _parser.Assign("advertiseName", advertises[i].Name);
                    _parser.Assign("advertiseDescription", advertises[i].Description);
                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Content.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Content.Table.Paging");
                _parser.Parse("Main.Content.Table");
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadAdvertiseByID(long? ID)
    {
        try
        {
            if (ID == null) //AddNew
            {
                _parser.Assign("advertiseName", string.Empty);
                _parser.Assign("advertiseDescription", string.Empty);
                _parser.Assign("advertiseContent", string.Empty);
                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm");
                _parser.Parse("Main.AddNewAdvertise");
            }
            else //Edit
            {
                Advertises advertise = _DR.Advertises.Where(a => a.ID.Equals(ID.Value)).FirstOrDefault();

                if (advertise == null)
                {
                    _parser.Parse("Main.Content.Error");
                }
                else
                {
                    _parser.Assign("advertiseID", advertise.ID.ToString());
                    _parser.Assign("advertiseName", advertise.Name);
                    _parser.Assign("advertiseDescription", advertise.Description);
                    _parser.Assign("advertiseContent", advertise.Content);                  

                    _parser.Parse("Main.Content.EditForm.Edit");
                    _parser.Parse("Main.Content.EditForm.ConfirmPassword");
                    _parser.Parse("Main.Content.EditForm");
                    _parser.Parse("Main.EditAdvertise");
                }
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteAdvertiseByID(long ID)
    {
        try
        {
            Advertises advertise = _DR.Advertises.Where(a => a.ID.Equals(ID)).FirstOrDefault();

            if (advertise != null)
            {
                _DR.DeleteObject(advertise);
                _DR.SaveChanges();
            }

            advertise = null;

            Response.Redirect("advertise.aspx");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
}